package com.lyrcsoft.application.service;

import com.lyrcsoft.spring.beans.annotation.MyCustomValue;
import com.lyrcsoft.spring.beans.factory.BeanPostProcessor;
import com.lyrcsoft.spring.stereotype.Component;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * 自定义的后置处理器
 *
 * @author fujc-dev@qq.com
 * @version 1.0
 */
@Component
public class LyrcSoftBeanPostProcessor implements BeanPostProcessor {

	@Override
	public Object postProcessBeforeInitialization(Object bean, String beanName) {
		System.out.println("postProcessBeforeInitialization：" + beanName);

		for (Field field : bean.getClass().getDeclaredFields()) {
			if (field.isAnnotationPresent(MyCustomValue.class)) {
				field.setAccessible(true);
				try {
					field.set(bean, field.getAnnotation(MyCustomValue.class).value());
				} catch (IllegalAccessException e) {
					throw new RuntimeException(e);
				}
			}
		}
		return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
	}

	@Override
	public Object postProcessAfterInitialization(Object bean, String beanName) {
		System.out.println("LyrcSoftBeanPostProcessor：" + beanName);
		// 模拟AOP
		if (beanName.equals("anyDoService")) {
			Object newProxyInstance = Proxy.newProxyInstance(this.getClass().getClassLoader(), bean.getClass().getInterfaces(), new InvocationHandler() {
				@Override
				public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
					//
					System.out.println("执行切面逻辑");
					return method.invoke(bean, args);
				}
			});
			return newProxyInstance;
		}
		return BeanPostProcessor.super.postProcessBeforeInitialization(bean, beanName);
	}
}
